<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
	<title>收货</title>
	<style>
		:root {
			--primary: #ed781b;
			--primary-dark: #ed781b;
			--bg: #f7f8fa;
			--text: #1f2329;
			--muted: #8a8f98;
			--border: #e5e6eb;
			--success: #16a34a;
			--danger: #ef4444;
		}
		* { box-sizing: border-box; }
		html, body { height: 100%; }
		body { margin: 0; background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Helvetica, Arial, sans-serif; }

		.container { min-height: 100%; padding: 160px 12px calc(16px + env(safe-area-inset-bottom)); }

		/* RF设备优化 - 减少顶部间距，避免重叠 */
		@media screen and (max-width: 480px) {
			.container { padding-top: 140px; }
			.page-header { height: 50px; }
		}

		/* 手机端优化 - 增加顶部间距 */
		@media screen and (min-width: 481px) {
			.container { padding-top: 180px; }
		}

		/* 超小屏幕RF设备进一步优化 */
		@media screen and (max-width: 360px) {
			.container { padding-top: 135px; }
			.page-header { height: 45px; padding: 10px 16px; }
		}

		/* 页面顶部样式 */
		.page-header {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 1000;
			background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
			padding: 16px 16px;
			box-shadow: 0 3px 10px rgba(44, 62, 80, 0.3);
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 60px;
		}
		.page-back-btn {
			background: rgba(255, 255, 255, 0.2);
			color: #fff;
			border: 2px solid rgba(255, 255, 255, 0.3);
			border-radius: 12px;
			padding: 10px 16px;
			font-size: 16px;
			font-weight: 600;
			transition: all 0.3s ease;
			backdrop-filter: blur(10px);
		}
		.page-back-btn:hover {
			background: rgba(255, 255, 255, 0.3);
			border-color: rgba(255, 255, 255, 0.5);
			transform: translateY(-1px);
		}
		.page-back-btn:active {
			background: rgba(255, 255, 255, 0.4);
			transform: translateY(0) scale(0.98);
		}
		.page-title {
			color: #fff;
			font-size: 14px;
			font-weight: 600;
			margin: 0;
			text-shadow: 0 1px 2px rgba(0,0,0,0.3);
		}
		.page-refresh-btn {
			background: rgba(255, 255, 255, 0.2);
			color: #fff;
			border: 2px solid rgba(255, 255, 255, 0.3);
			border-radius: 12px;
			padding: 10px 16px;
			font-size: 14px;
			font-weight: 600;
			transition: all 0.3s ease;
			backdrop-filter: blur(10px);
		}
		.page-refresh-btn:hover {
			background: rgba(255, 255, 255, 0.3);
			border-color: rgba(255, 255, 255, 0.5);
			transform: translateY(-1px);
		}
		.page-refresh-btn:active {
			background: rgba(255, 255, 255, 0.4);
			transform: translateY(0) scale(0.98);
		}

		/* 订单查询搜索区域 - 固定在顶部第二排 */
		.order-search-section {
			position: fixed;
			top: 60px;
			left: 0;
			right: 0;
			z-index: 999;
			background: #f5f5f5;
			padding: 12px 16px;
			box-shadow: 0 2px 4px rgba(0,0,0,0.1);
			height: 68px;
			box-sizing: border-box;
		}
		.order-search-container {
			display: flex;
			gap: 12px;
			align-items: center;
		}
		.order-search-input-wrapper {
			flex: 1;
			position: relative;
		}
		.order-search-input-wrapper::before {
			content: '🔍';
			position: absolute;
			left: 12px;
			top: 50%;
			transform: translateY(-50%);
			font-size: 16px;
			opacity: 0.5;
			pointer-events: none;
		}
		.order-search-input {
			width: 100%;
			height: 44px;
			padding: 0 12px 0 40px;
			border: 1px solid var(--border);
			border-radius: 8px;
			font-size: 15px;
			background: #fff;
			transition: border-color 0.2s ease;
		}
		.order-search-input:focus {
			outline: none;
			border-color: var(--primary);
		}
		.order-search-btn {
			height: 44px;
			padding: 0 20px;
			border: 0;
			background: var(--primary);
			color: #fff;
			border-radius: 8px;
			font-size: 15px;
			font-weight: 500;
			transition: all 0.2s ease;
			white-space: nowrap;
		}
		.order-search-btn:active {
			background: var(--primary-dark);
			transform: scale(0.98);
		}

		/* 移动端优化 */
		@media (max-width: 768px) {
			.order-search-section {
				padding: 10px 12px;
			}
			.order-search-container {
				gap: 8px;
			}
			.order-search-input {
				height: 40px;
				font-size: 14px;
			}
			.order-search-btn {
				height: 40px;
				padding: 0 16px;
				font-size: 14px;
			}
		}

		/* RF设备优化 */
		@media screen and (max-width: 480px) {
			.order-search-section {
				top: 50px;
				height: 64px;
			}
			/* RF设备订单列表间距调整 */
			#orderListView { margin-top: 45px; }
			#listView { margin-top: 20px; }
		}
		@media screen and (max-width: 360px) {
			.order-search-section {
				top: 45px;
				height: 64px;
			}
			/* 超小屏幕订单列表间距调整 */
			#orderListView { margin-top: 20px; }
			#listView { margin-top: 20px; }
		}

		.header { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; margin-top: 0; padding: 12px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
		.order { font-weight: 600; font-size: 18px; color: var(--text); }
		.refresh-btn { margin-left: auto; background: var(--primary); color: #fff; border: 0; border-radius: 8px; padding: 10px 16px; font-size: 14px; font-weight: 500; }
		.refresh-btn:active { background: var(--primary-dark); transform: scale(0.98); }

		.card { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
		.list { display: flex; flex-direction: column; gap: 12px; margin-top: 20px; }
		/* 订单列表有搜索框，需要更大的间距 */
		#orderListView { margin-top: 20px; }
		/* 商品列表没有搜索框，使用较小的间距 */
		#listView { margin-top: 20px; }
		.item { display: flex; align-items: center; gap: 12px; padding: 16px; border: 1px solid var(--border); border-radius: 12px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); transition: all 0.2s ease; }
		.item:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); transform: translateY(-1px); }
		.item-title { font-weight: 600; font-size: 16px; color: var(--text); }
		.item-sub { color: var(--muted); font-size: 13px; margin-top: 4px; }
		.item-qty { margin-left: auto; text-align: right; font-size: 13px; color: var(--muted); }
		.item-qty b { display: inline-block; min-width: 40px; color: var(--text); font-weight: 600; }
		.item-enter { background: var(--primary); color: #fff; border: 0; border-radius: 10px; padding: 10px 16px; font-size: 14px; margin-left: 12px; font-weight: 500; transition: all 0.2s ease; }
		.item-enter:active { background: var(--primary-dark); transform: scale(0.98); }
		.item-enter:disabled { background: #ccc; cursor: not-allowed; transform: none; }

		.detail { display: none; gap: 16px; margin-top: 40px; }
		.detail .head { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; padding: 16px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
		.detail .head-top { display: flex; align-items: center; gap: 12px; }
		.back { border: 1px solid var(--border); background: #fff; border-radius: 10px; padding: 10px 14px; font-size: 14px; font-weight: 500; transition: all 0.2s ease; }
		.back:active { background: #f5f5f5; transform: scale(0.98); }
		.code { font-weight: 700; font-size: 18px; color: var(--text); flex: 1; }
		.stat { display: flex; flex-direction: column; gap: 4px; color: var(--muted); font-size: 12px; }
		.stat > div { display: flex; align-items: center; }
		.stat b { color: var(--text); font-weight: 600; font-size: 13px; margin-left: 4px; }

		.scan-section { margin: 16px 0; }
		.scan { display: flex; flex-direction: column; gap: 8px; padding: 16px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
		.scan-input-container { display: flex; gap: 12px; align-items: center; }
		.scan-tip { font-size: 12px; color: var(--muted); text-align: center; margin-bottom: 4px; }
		.scan input { flex: 1; height: 48px; padding: 0 16px; border: 2px solid var(--border); border-radius: 12px; font-size: 16px; transition: border-color 0.2s ease; }
		.scan input:focus { outline: none; border-color: var(--primary); }
		.scan button { height: 48px; padding: 0 20px; border: 0; background: var(--primary); color: #fff; border-radius: 12px; font-size: 16px; font-weight: 500; transition: all 0.2s ease; }
		.scan button:active { background: var(--primary-dark); transform: scale(0.98); }
		.scan button:disabled { background: #ccc; cursor: not-allowed; transform: none; }

		/* 移动端优化 - 参考图片样式 */
		@media (max-width: 768px) {
			.scan-section { margin: 12px 0; }
			.scan { padding: 12px; }
			.scan-input-container { gap: 8px; }
			.scan input { height: 44px; font-size: 15px; }
			.scan button { height: 44px; font-size: 15px; padding: 0 16px; }
		}

		.tabs { display: flex; gap: 8px; background: #fff; padding: 8px; border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
		.tab { flex: 1; text-align: center; padding: 12px; border-radius: 10px; font-size: 14px; color: var(--muted); background: #f7f8fa; font-weight: 500; transition: all 0.2s ease; }
		.tab.active { color: #fff; background: var(--primary); transform: scale(1.02); }

		.sn-list { margin-top: 16px; }
		.sn-ul { list-style: none; padding: 0; margin: 0; display: none; max-height: 50vh; overflow: auto; border: 1px solid var(--border); border-radius: 12px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
		.sn-ul.active { display: block; }
		.sn-ul li { padding: 14px 16px; border-bottom: 1px solid var(--border); font-size: 15px; color: var(--text); transition: background-color 0.2s ease; }
		.sn-ul li:last-child { border-bottom: 0; }
		.sn-ul li:hover { background-color: #f8f9fa; }

		.footer { margin-top: 16px; text-align: center; color: var(--muted); font-size: 12px; }
		.toast { position: fixed; left: 50%; bottom: calc(30px + env(safe-area-inset-bottom)); transform: translateX(-50%); background: rgba(0,0,0,.85); color: #fff; padding: 12px 20px; border-radius: 25px; font-size: 14px; display: none; z-index: 9999; font-weight: 500; box-shadow: 0 4px 20px rgba(0,0,0,0.3); }

		/* SN确认弹窗样式 */
		.sn-confirm-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 10000; padding: 20px; }
		.sn-confirm-modal.active { display: flex; }
		.sn-confirm-content { background: #fff; border-radius: 16px; padding: 24px; max-width: 400px; width: 100%; box-shadow: 0 8px 32px rgba(0,0,0,0.2); }
		.sn-confirm-header { font-weight: 600; font-size: 18px; margin-bottom: 20px; text-align: center; color: var(--text); }
		.sn-confirm-body { margin-bottom: 24px; }
		.sn-confirm-label { font-size: 14px; color: var(--muted); margin-bottom: 8px; display: block; }
		.sn-confirm-input { width: 100%; height: 48px; padding: 0 16px; border: 2px solid var(--border); border-radius: 12px; font-size: 16px; transition: border-color 0.2s ease; }
		.sn-confirm-input:focus { outline: none; border-color: var(--primary); }
		.sn-confirm-footer { display: flex; gap: 12px; }
		.sn-confirm-btn { flex: 1; height: 48px; border: 0; border-radius: 12px; font-size: 16px; font-weight: 500; transition: all 0.2s ease; }
		.sn-confirm-btn-primary { background: var(--primary); color: #fff; }
		.sn-confirm-btn-primary:active { background: var(--primary-dark); transform: scale(0.98); }
		.sn-confirm-btn-secondary { background: var(--border); color: var(--text); }
		.sn-confirm-btn-secondary:active { background: var(--muted); transform: scale(0.98); }

		/* 移动端优化 */
		@media (max-width: 768px) {
			.container { padding: 8px 8px calc(12px + env(safe-area-inset-bottom)); }
			.header { margin-bottom: 12px; padding: 10px; }
			.order { font-size: 16px; }
			.item { padding: 14px; }
			.item-title { font-size: 15px; }
			.scan input { height: 44px; font-size: 15px; }
			.scan button { height: 44px; font-size: 15px; }
			/* 移动端订单列表间距调整 */
			#orderListView { margin-top: 20px; }
			#listView { margin-top: 20px; }
		}

		/* 触摸设备优化 */
		@media (hover: none) and (pointer: coarse) {
			.item:hover { transform: none; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
			.item:active { transform: scale(0.98); }
		}
	</style>
</head>
<body>
	<div class="container">
		<!-- 页面顶部导航 -->
		<div class="page-header">
			<button class="page-back-btn" id="pageBackBtn">←</button>
			<h1 class="page-title">屏体入库单</h1>
			<button class="page-refresh-btn" id="refreshBtn">刷新</button>
		</div>

		<!-- 订单查询搜索区域 - 固定在顶部第二排 -->
		<div class="order-search-section" id="orderSearchSection" style="display:none;">
			<div class="order-search-container">
				<div class="order-search-input-wrapper">
					<input type="text" id="orderSearchInput" class="order-search-input" placeholder="请输入订单号或客户单号" autocomplete="off" />
				</div>
				<button class="order-search-btn" id="orderSearchBtn">查询</button>
			</div>
		</div>

		<div class="header" style="display:none;">
			<button class="back" id="backToOrdersListBtn" style="display:none; margin-left:8px;">订单</button>
		</div>

		<div id="orderListView" class="list"></div>
		<div id="listView" class="list" style="display:none"></div>

		<div id="detailView" class="detail">
			<div class="card" style="flex:1; width:100%">
				<!-- 扫码输入区域 -->
				<div class="scan-section">
					<div class="scan">
						<div class="scan-tip">扫码或输入SN，回车确认</div>
						<div class="scan-input-container">
							<input id="snInput" type="text" inputmode="text" autocomplete="off" placeholder="请输入或扫描SN" />
							<button id="scanBtn">确定</button>
						</div>
					</div>
				</div>

				<div class="head">
					<div class="head-top">
						<button class="back" id="backBtn">返回</button>
						<div class="code" id="skuCode">-</div>
					</div>
					<div class="stat">
						<div>需收货总数：<b id="planQty">0</b></div>
						<div>已收货数量：<b id="receivedQty">0</b></div>
						<div>待收货数量：<b id="pendingQty">0</b></div>
					</div>
				</div>

				<div class="tabs">
 					<div class="tab active" data-tab="pending">待收货SN（<span id="pendingCount">0</span>）</div>
				</div>

				<div class="sn-list">
					<ul id="pendingList" class="sn-ul active"></ul>
				</div>
			</div>
		</div>

<!--		<div class="footer">为移动端优化 · 支持扫码枪回车</div>-->
	</div>
	<div class="toast" id="toast"></div>

	<!-- SN确认弹窗 -->
	<div class="sn-confirm-modal" id="snConfirmModal">
		<div class="sn-confirm-content">
			<div class="sn-confirm-header">确认SN</div>
			<div class="sn-confirm-body">
				<label class="sn-confirm-label">请输入或修改SN：</label>
				<input type="text" id="snConfirmInput" class="sn-confirm-input" placeholder="请输入SN" autocomplete="off" />
			</div>
			<div class="sn-confirm-footer">
				<button class="sn-confirm-btn sn-confirm-btn-secondary" id="snCancelBtn">返回</button>
				<button class="sn-confirm-btn sn-confirm-btn-primary" id="snConfirmBtn">确认</button>
			</div>
		</div>
	</div>

	<!-- jQuery CDN for older browser compatibility -->
	<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
	<script>
		// 使用本地反向代理以避免跨域
		var endpoints = {
			orders: function(whCode, userCode) { return '/upload/api/orders?whCode=' + encodeURIComponent(whCode) + '&userCode=' + encodeURIComponent(userCode); },
			itemsByOrder: function(projectId, asnNo) { return '/upload/api/items?projectId=' + encodeURIComponent(projectId) + '&asnNo=' + encodeURIComponent(asnNo); },
			pendingSNs: function(projectId, asnNo, skuCode) { return '/upload/api/pendingSNs?projectId=' + encodeURIComponent(projectId) + '&asnNo=' + encodeURIComponent(asnNo) + '&skuCode=' + encodeURIComponent(skuCode); },
			receiveBySN: function() { return '/upload/api/receive'; }
		};

		var state = {
			projectId: '',
			whCode: '',
			userCode: '',
			orders: [],
			allOrders: [], // 保存所有订单数据，用于搜索过滤
			orderNo: '',
			orderType: '',
			items: [],
			current: null // { skuCode, planQty, receivedQty, pendingQty, receivedSNs:[], pendingSNs:[] }
		};

		function showToast(msg) {
			$('#toast').text(msg).show();
			setTimeout(function() { $('#toast').hide(); }, 1500);
		}

		function getQuery(name) {
			// 兼容误写成 ??projectId=xxx 或多余的 ?
			var href = location.href.replace(/\?\?+/, '?');
			// 使用正则表达式提取参数值，兼容旧浏览器
			var regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i');
			var match = href.match(regex);
			return match ? decodeURIComponent(match[1]) : '';
		}

		function fetchJSON(url, options) {
			return $.ajax({
				url: url,
				type: options && options.method ? options.method : 'GET',
				dataType: 'json',
				data: options && options.body ? options.body : null,
				contentType: options && options.headers && options.headers['Content-Type'] ? options.headers['Content-Type'] : 'application/json',
				headers: options && options.headers ? options.headers : {}
			}).fail(function(xhr, status, error) {
				console.error('请求失败', error);
				throw new Error('HTTP ' + xhr.status);
			});
		}

		// 预留：如需本地联调可补充 mock
		function loadOrders() {
			$('#orderListView').empty();
			console.log('开始加载订单，参数:', { whCode: state.whCode, userCode: state.userCode });
			var apiUrl = endpoints.orders(state.whCode, state.userCode);
			console.log('API URL:', apiUrl);

			fetchJSON(apiUrl).done(function(data) {
				state.allOrders = Array.isArray(data) ? data : [];
				state.orders = state.allOrders; // 初始显示所有订单
				console.log('获取到的订单数据:', data);

				// 从第一个订单中获取projectId
				if (state.orders.length > 0 && state.orders[0].projectId) {
					state.projectId = state.orders[0].projectId;
					console.log('从订单数据中获取projectId:', state.projectId);
				}

				renderOrders();
			}).fail(function(e) {
				console.error('加载订单失败:', e);
				$('#orderListView').html('<div class="card">订单加载失败，请检查网络</div>');
				showToast('加载订单失败');
			});
		}

		function renderOrders() {
			var listEl = $('#orderListView');
			if (!state.orders.length) {
				listEl.html('<div class="card">没有找到相关订单</div>');
				return;
			}

			var html = '';
			for (var i = 0; i < state.orders.length; i++) {
				var order = state.orders[i];
				html += '<div class="item" data-order="' + (order.orderNo || '') + '">' +
					'<div style="flex: 1;">' +
						'<div class="item-title">' + (order.orderNo || '-') + '</div>' +
						'<div class="item-sub">客户单号：' + (order.logisticNo || '-') + '</div>' +
						'<div class="item-sub" style="margin-top: 2px;">订单类型：' + (order.orderType || '-') + '</div>' +
					'</div>' +
					'<button class="item-enter">进入</button>' +
				'</div>';
			}
			listEl.html(html);

			// 绑定事件
			listEl.find('.item-enter').on('click', function(e) {
				e.stopPropagation();
				var orderNo = $(this).closest('.item').data('order');
				console.log('点击进入按钮:', orderNo);
				selectOrder(orderNo);
			});

			listEl.find('.item').on('click', function(e) {
				if (!$(e.target).is('button')) {
					var orderNo = $(this).data('order');
					console.log('点击订单行:', orderNo);
					selectOrder(orderNo);
				}
			});
		}

		function selectOrder(orderNo) {
			state.orderNo = orderNo;
			var ord = null;
			for (var i = 0; i < state.orders.length; i++) {
				if (state.orders[i].orderNo === orderNo) {
					ord = state.orders[i];
					break;
				}
			}
			state.orderType = ord && ord.orderType ? String(ord.orderType) : '';
			console.log('选择订单:', orderNo);
			$('#orderListView').hide();
			$('#orderSearchSection').hide(); // 隐藏搜索区域
			$('#detailView').hide();
			$('#listView').show();
			$('#backToOrdersListBtn').show();
			loadList();
		}

		function loadList() {
			var orderNo = state.orderNo;
			$('#listView').empty();
			console.log('加载商品列表，参数:', { projectId: state.projectId, orderNo: orderNo });

			fetchJSON(endpoints.itemsByOrder(state.projectId, orderNo)).done(function(data) {
				// 映射至前端所需字段
				var raw = Array.isArray(data) ? data : [];
				state.items = [];
				for (var i = 0; i < raw.length; i++) {
					var it = raw[i];
					state.items.push({
						skuCode: it.skuCode,
						planQty: Number(it.qtyAsnEa || 0),
						receivedQty: Number(it.qtyRcvEa || 0),
						pendingQty: Number(it.qtyNoEa || Math.max(0, (it.qtyAsnEa || 0) - (it.qtyRcvEa || 0)))
					});
				}
				renderList();
			}).fail(function(e) {
				$('#listView').html('<div class="card">商品加载失败，请检查网络或跨域（CORS）设置</div>');
				showToast('加载商品失败');
			});
		}

		function renderList() {
			var listEl = $('#listView');
			if (!state.items.length) {
				listEl.html('<div class="card">没有找到相关商品</div>');
				return;
			}

			var html = '';
			for (var i = 0; i < state.items.length; i++) {
				var item = state.items[i];
				var isCompleted = (item.pendingQty || 0) <= 0;
				var buttonText = isCompleted ? '已收齐' : '进入';
				var buttonDisabled = isCompleted ? 'disabled' : '';

				html += '<div class="item" data-sku="' + (item.skuCode || '') + '">' +
					'<div>' +
						'<div class="item-title">' + (item.skuCode || '-') + '</div>' +
						'<div class="item-sub">商品代码</div>' +
					'</div>' +
					'<div class="item-qty">' +
						'<div>需收 <b>' + (item.planQty || 0) + '</b></div>' +
						'<div>已收 <b>' + (item.receivedQty || 0) + '</b></div>' +
						'<div>待收 <b>' + (item.pendingQty || 0) + '</b></div>' +
					'</div>' +
					'<button class="item-enter" ' + buttonDisabled + '>' + buttonText + '</button>' +
				'</div>';
			}
			listEl.html(html);

			// 绑定事件
			listEl.find('.item-enter:not([disabled])').on('click', function() {
				var skuCode = $(this).closest('.item').data('sku');
				enterDetail(skuCode);
			});

			listEl.find('.item').on('click', function(e) {
				if (!$(e.target).is('button')) {
					var skuCode = $(this).data('sku');
					var item = null;
					for (var j = 0; j < state.items.length; j++) {
						if (state.items[j].skuCode === skuCode) {
							item = state.items[j];
							break;
						}
					}
					if (item && (item.pendingQty || 0) <= 0) {
						showToast('该SKU已收齐');
					} else {
						enterDetail(skuCode);
					}
				}
			});
		}

		function enterDetail(skuCode) {
			// 根据列表已有数量进入详情，并加载待收SN列表
			var it = null;
			for (var i = 0; i < state.items.length; i++) {
				if (state.items[i].skuCode === skuCode) {
					it = state.items[i];
					break;
				}
			}

			state.current = {
				skuCode: skuCode,
				planQty: Number(it && it.planQty ? it.planQty : 0),
				receivedQty: Number(it && it.receivedQty ? it.receivedQty : 0),
				pendingQty: Number(it && it.pendingQty ? it.pendingQty : Math.max(0, (it && it.planQty ? it.planQty : 0) - (it && it.receivedQty ? it.receivedQty : 0))),
				receivedSNs: [],
				pendingSNs: []
			};

			$('#listView').hide();
			$('#scanSection').hide();
			$('#detailView').show();
			renderDetail();
			setTimeout(function() { $('#snInput').focus(); }, 50);
			loadPendingSNs();
		}

		function loadPendingSNs() {
			if (!state.current) return;

			fetchJSON(endpoints.pendingSNs(state.projectId, state.orderNo, state.current.skuCode)).done(function(data) {
				// 接口返回数组，字段 skuCode 实际承载 SN 值
				var arr = Array.isArray(data) ? data : [];
				state.current.pendingSNs = [];
				for (var i = 0; i < arr.length; i++) {
					if (arr[i].skuCode) {
						state.current.pendingSNs.push(arr[i].skuCode);
					}
				}
				$('#pendingCount').text(state.current.pendingSNs.length);
				renderDetail();
			}).fail(function(e) {
				// 静默失败即可，已显示数量
			});
		}

		function renderDetail() {
			var cur = state.current;
			if (!cur) return;

			$('#skuCode').text(cur.skuCode);
			$('#planQty').text(cur.planQty);
			$('#receivedQty').text(cur.receivedQty);
			$('#pendingQty').text(cur.pendingQty);
			$('#pendingCount').text(cur.pendingSNs.length);

			var pList = $('#pendingList');
			pList.empty();

			for (var i = 0; i < cur.pendingSNs.length; i++) {
				pList.append('<li>' + cur.pendingSNs[i] + '</li>');
			}
		}

		// 显示SN确认弹窗
		function showSNConfirmModal(sn) {
			$('#snConfirmInput').val(sn);
			$('#snConfirmModal').addClass('active');
			setTimeout(function() {
				$('#snConfirmInput').focus();
				$('#snConfirmInput').select();
			}, 100);
		}

		// 关闭SN确认弹窗
		function closeSNConfirmModal() {
			$('#snConfirmModal').removeClass('active');
			$('#snInput').val('');
			setTimeout(function() {
				$('#snInput').focus();
			}, 100);
		}

		// 实际执行收货操作
		function doReceiveSN(sn) {
			if (!sn) { 
				showToast('请输入/扫码SN'); 
				return; 
			}
			// 校验SN格式：只允许数字、字母和连字符
			if (!/^[A-Za-z0-9\-]+$/.test(sn)) {
				showToast('SN只能包含数字、字母和连字符');
				return;
			}
			if (!state.current) {
				showToast('请先选择商品');
				return;
			}

			// 业务校验：屏体转仓单 必须在待收SN列表里
			if (state.orderType === '屏体转仓单') {
				// 当待收SN列表为空时，无需校验
				if (state.current.pendingSNs && state.current.pendingSNs.length > 0) {
					var inPending = false;
					for (var i = 0; i < (state.current.pendingSNs || []).length; i++) {
						if (state.current.pendingSNs[i] === sn) {
							inPending = true;
							break;
						}
					}
					if (!inPending) {
						showToast('收货无此SN');
						return;
					}
				}
			}

			var btn = $('#scanBtn');
			var input = $('#snInput');
			btn.prop('disabled', true);
			input.prop('disabled', true);
			$('#snConfirmBtn').prop('disabled', true);

			var payload = {
				projectId: String(state.projectId || ''),
				asnNo: String(state.orderNo || ''),
				skuCode: String(state.current.skuCode || ''),
				snCode: sn,
				userCode: String(state.userCode || '')
			};

			console.log('发送收货请求:', payload);

			$.ajax({
				url: endpoints.receiveBySN(),
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify(payload),
				dataType: 'json'
			}).done(function(response) {
				// 解析JSON响应，检查success字段
				var success = false;
				var message = '收货失败';

				if (response && typeof response === 'object') {
					success = response.success === true;
					if (response.message) {
						message = response.message;
					}
				} else if (typeof response === 'string') {
					// 兼容旧格式：检查字符串中是否包含"操作成功"
					success = response.indexOf && response.indexOf('操作成功') !== -1;
				}

				if (!success) {
					// 失败时显示服务器的message信息
					showToast(message);
					// 注意：不要在这里return，让always块执行以恢复按钮状态
				} else {
					// 成功：关闭弹窗，刷新数量与SN列表，再根据数量决定返回或继续扫描
					closeSNConfirmModal();
					reloadQuantitiesAndSNs().done(function() {
						if (state.current && (state.current.pendingQty <= 0 || state.current.receivedQty >= state.current.planQty)) {
							// 本SKU已完成，返回到商品列表
							$('#detailView').hide();
							$('#listView').show();
							showToast('本SKU已收齐');
						} else {
							showToast('收货成功');
						}
					});
				}
			}).fail(function(xhr, status, error) {
				console.error('收货请求失败:', status, error);
				showToast('收货失败，请重试');
			}).always(function() {
				btn.prop('disabled', false);
				input.prop('disabled', false);
				$('#snConfirmBtn').prop('disabled', false);
				// 如果弹窗还开着，聚焦到弹窗输入框；否则聚焦到主输入框
				if ($('#snConfirmModal').hasClass('active')) {
					setTimeout(function() {
						$('#snConfirmInput').focus();
					}, 100);
				} else {
					setTimeout(function() {
						input.focus();
					}, 100);
				}
			});
		}

		function submitSN() {
			var input = $('#snInput');
			var sn = input.val().trim();
			if (!sn) { showToast('请输入/扫码SN'); return; }
			// 校验SN格式：只允许数字、字母和连字符
			if (!/^[A-Za-z0-9\-]+$/.test(sn)) {
				input.val('');
				showToast('SN只能包含数字、字母和连字符');
				return;
			}
			if (!state.current) return;

			// 显示确认弹窗
			showSNConfirmModal(sn);
		}

		function reloadQuantitiesAndSNs() {
			// 重新加载订单明细数量
			return fetchJSON(endpoints.itemsByOrder(state.projectId, state.orderNo)).done(function(data) {
				// 映射至前端所需字段
				var raw = Array.isArray(data) ? data : [];
				state.items = [];
				for (var i = 0; i < raw.length; i++) {
					var it = raw[i];
					state.items.push({
						skuCode: it.skuCode,
						planQty: Number(it.qtyAsnEa || 0),
						receivedQty: Number(it.qtyRcvEa || 0),
						pendingQty: Number(it.qtyNoEa || Math.max(0, (it.qtyAsnEa || 0) - (it.qtyRcvEa || 0)))
					});
				}

				// 同步当前 SKU 的数量
				var it = null;
				if (state.current) {
					for (var i = 0; i < state.items.length; i++) {
						if (state.items[i].skuCode === state.current.skuCode) {
							it = state.items[i];
							break;
						}
					}
				}

				if (it && state.current) {
					state.current.planQty = it.planQty;
					state.current.receivedQty = it.receivedQty;
					state.current.pendingQty = it.pendingQty;
				}

				renderDetail();
				// 重新加载待收SN
				loadPendingSNs();
			}).fail(function(e) {
				console.error('重新加载数量失败:', e);
			});
		}

		function bindEvents() {
			// 页面返回按钮事件 - 针对RF巴枪优化
			$('#pageBackBtn').on('click', function() {
				// 如果当前在商品列表界面，返回到订单列表
				if ($('#listView').is(':visible')) {
					state.current = null;
					$('#detailView').hide();
					$('#listView').hide();
					$('#orderListView').show();
					$('#orderSearchSection').show(); // 显示搜索区域
					$('#backToOrdersListBtn').hide();
					return;
				}

				// 如果当前在详情界面，返回到商品列表
				if ($('#detailView').is(':visible')) {
					$('#detailView').hide();
					$('#listView').show();
					return;
				}

				// 如果当前在订单列表界面，执行原来的返回逻辑
				// 优先尝试调用RF巴枪app的返回方法
				try {
					// 方法1: 尝试调用Android WebView的返回方法
					if (typeof Android !== 'undefined' && Android.goBack) {
						Android.goBack();
						return;
					}

					// 方法2: 尝试调用iOS WKWebView的返回方法
					if (typeof webkit !== 'undefined' && webkit.messageHandlers && webkit.messageHandlers.goBack) {
						webkit.messageHandlers.goBack.postMessage({});
						return;
					}

					// 方法3: 尝试调用自定义的返回方法
					if (typeof window.goBack === 'function') {
						window.goBack();
						return;
					}

					// 方法4: 尝试调用cordova/phonegap的返回方法
					if (typeof cordova !== 'undefined' && cordova.exec) {
						cordova.exec(null, null, 'Device', 'goBack', []);
						return;
					}

					// 方法5: 使用window.history.back()作为兜底
					if (window.history && window.history.back) {
						window.history.back();
						return;
					}

					// 方法6: 最后兜底方案 - 关闭窗口
					window.close();

				} catch (e) {
					// 异常处理：尝试最基本的返回方法
					try {
						window.history.back();
					} catch (e2) {
						window.close();
					}
				}
			});

			$('#refreshBtn').on('click', function() {
				if (state.projectId && !state.orderNo) return loadOrders();
				if (!state.current) return loadList();
				reloadQuantitiesAndSNs();
			});

			$('#backBtn').on('click', function() {
				$('#detailView').hide();
				$('#listView').show();
			});

			$('#backToOrdersListBtn').on('click', function() {
				state.current = null;
				$('#detailView').hide();
				$('#listView').hide();
				$('#orderListView').show();
				$('#orderSearchSection').show(); // 显示搜索区域
				$('#backToOrdersListBtn').hide();
			});

			$('#scanBtn').on('click', submitSN);

			$('#snInput').on('keydown', function(e) {
				if (e.key === 'Enter') submitSN();
			});

			// SN确认弹窗事件
			$('#snConfirmBtn').on('click', function() {
				var sn = $('#snConfirmInput').val().trim();
				doReceiveSN(sn);
			});

			$('#snCancelBtn').on('click', function() {
				closeSNConfirmModal();
			});

			$('#snConfirmInput').on('keydown', function(e) {
				if (e.key === 'Enter') {
					var sn = $('#snConfirmInput').val().trim();
					doReceiveSN(sn);
				} else if (e.key === 'Escape') {
					closeSNConfirmModal();
				}
			});

			// 实时过滤SN输入，只允许数字、字母和连字符
			$('#snConfirmInput').on('input', function(e) {
				var input = $(this);
				var val = input.val();
				// 只保留数字、字母和连字符
				var filtered = val.replace(/[^A-Za-z0-9\-]/g, '');
				if (val !== filtered) {
					input.val(filtered);
					showToast('SN只能包含数字、字母和连字符');
				}
			});
			// 实时过滤SN输入，只允许数字、字母和连字符
			$('#snInput').on('input', function(e) {
				var input = $(this);
				var val = input.val();
				// 只保留数字、字母和连字符
				var filtered = val.replace(/[^A-Za-z0-9\-]/g, '');
				if (val !== filtered) {
					input.val(filtered);
					showToast('SN只能包含数字、字母和连字符');
				}
			});

			$('.tab').on('click', function() {
				$('.tab').removeClass('active');
				$(this).addClass('active');
				$('.sn-ul').removeClass('active');
				var tabType = $(this).data('tab');
				$('#' + (tabType === 'received' ? 'receivedList' : 'pendingList')).addClass('active');
			});

			// 订单查询功能
			$('#orderSearchBtn').on('click', function() {
				performOrderSearch();
			});

			$('#orderSearchInput').on('keydown', function(e) {
				if (e.key === 'Enter') {
					performOrderSearch();
				}
			});

			// 清空搜索时显示所有订单
			$('#orderSearchInput').on('input', function() {
				var val = $(this).val().trim();
				if (!val) {
					state.orders = state.allOrders;
					renderOrders();
				}
			});
		}

		// 执行订单搜索
		function performOrderSearch() {
			var keyword = $('#orderSearchInput').val().trim();
			if (!keyword) {
				// 如果搜索关键词为空，显示所有订单
				state.orders = state.allOrders;
				renderOrders();
				return;
			}

			// 模糊搜索：匹配订单号或客户单号
			var filtered = [];
			for (var i = 0; i < state.allOrders.length; i++) {
				var order = state.allOrders[i];
				var orderNo = (order.orderNo || '').toLowerCase();
				var logisticNo = (order.logisticNo || '').toLowerCase();
				var keywordLower = keyword.toLowerCase();

				if (orderNo.indexOf(keywordLower) !== -1 || logisticNo.indexOf(keywordLower) !== -1) {
					filtered.push(order);
				}
			}

			state.orders = filtered;
			renderOrders();

			if (filtered.length === 0) {
				showToast('未找到匹配的订单');
			}
		}

		function init() {
			state.projectId = getQuery('projectId') || getQuery('projectid') || '';
			state.whCode = getQuery('whCode') || getQuery('whcode') || '';
			state.userCode = getQuery('userCode') || getQuery('usercode') || '';
			state.orderNo = getQuery('orderNo') || getQuery('orderno') || getQuery('order_no') || '';

			console.log('获取到的参数:', {
				projectId: state.projectId,
				whCode: state.whCode,
				userCode: state.userCode,
				orderNo: state.orderNo
			});

			bindEvents();
			// 检查是否有查询参数
			var hasWhCode = getQuery('whCode') || getQuery('whcode');
			var hasUserCode = getQuery('userCode') || getQuery('usercode');
			var hasProjectId = state.projectId;

			if ((hasProjectId || hasWhCode || hasUserCode) && !state.orderNo) {
				$('#orderListView').show();
				$('#listView').hide();
				$('#detailView').hide();
				$('#orderSearchSection').show(); // 显示搜索区域
				loadOrders();
			} else if (state.orderNo) {
				$('#orderListView').hide();
				$('#listView').show();
				loadList();
			} else {
				$('#orderListView').show();
				$('#orderListView').html('<div class="card">未查询到单据</div>');
			}
		}

		// 等待jQuery加载完成后初始化
		$(document).ready(function() {
			init();
		});
	</script>
</body>
</html>